/* simplelog.h : dgnsc simple log
 * Copyright (C) 2009-2011 drangon <drangon.zhou@gmail.com>
 * 2011-09
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef INCLUDED_DGNSC_SIMPLELOG_H
#define INCLUDED_DGNSC_SIMPLELOG_H

#include <assert.h>
#define ASSERT(x) assert(x)

#ifdef _WIN32
#include <stdio.h>
#define DGNSC_SIMPLELOG( fmt, ... ) \
	do { \
		SYSTEMTIME mytm; \
		::GetLocalTime( &mytm ); \
		const char * p = strrchr( __FILE__, '\\' ); \
		if( p == NULL ) \
			p = strrchr( __FILE__, '/' ); \
		if( p == NULL ) \
			p = __FILE__; \
		else \
			p += 1; \
		char buf[1024]; \
		_snprintf_s( buf, sizeof(buf) - 1, _TRUNCATE, "[%02d%02d %02d:%02d:%02d.%03d][%s:%d] "fmt, \
				mytm.wMonth, mytm.wDay, mytm.wHour, mytm.wMinute, mytm.wSecond, mytm.wMilliseconds, \
				p, __LINE__, ##__VA_ARGS__ ); \
		buf[sizeof(buf) - 1] = '\0'; \
		OutputDebugStringA( buf ); \
	} while( 0 )

#else

#include <sys/types.h>
#include <unistd.h>
#include <syslog.h>

#ifndef DGNSC_LOG_FACILITY
#define DGNSC_LOG_FACILITY LOG_LOCAL5
#endif // APP_LOG_FACILITY

#define DGNSC_SIMPLELOG( fmt, ...)  \
	do { \
		struct timval tv; \
		gettimeofday( &tv, NULL ); \
		const char * p = strrchr( __FILE__, '/' ); \
		if( p == NULL ) \
			p = __FILE__; \
		else \
			p += 1; \
		syslog( DGNSC_LOG_FACILITY | LOG_ERR, \
				"[%06d] PID %d [%s:%d] "fmt, tv.tv_usec, getpid(), p, __LINE__, ##__VA_ARGS__ ); \
	} while( 0 )

#endif /* _WIN32 else */

#define PR_ERR( fmt, ... ) DGNSC_SIMPLELOG( "[ERR] "fmt, ##__VA_ARGS__ )
#define PR_DEBUG( fmt, ... ) DGNSC_SIMPLELOG( "[DEBUG] "fmt, ##__VA_ARGS__ )

#endif /* INCLUDED_DC_SIMPLELOG_H */

